<template>
	<!-- 启动检查时的加载状态 -->
	<view v-if="isChecking" class="loading">
		<u-loading-icon size="40" mode="circle"></u-loading-icon>
	</view>
	

	<!-- 主内容区 -->
	<view v-else class="container">
		<!-- 顶部欢迎区域 -->
		<view class="welcome-section">
			<view class="welcome-text">
				<text class="greeting">你好，</text>
				<text class="username">{{userInfo.name || '用户'}}</text>
			</view>
			<view class="user-avatar">
				<image :src="userInfo.avatar || '/static/logo.png'" mode="aspectFill" class="avatar"></image>
			</view>
		</view>

		<!-- 功能模块区域 -->
		<view class="modules-section">
			<!-- 咨询师列表模块 -->
			<view class="consultant-section">
				<view class="section-header">
					<text class="section-title">推荐咨询师</text>
					<view class="more-btn" @click="navigateToList">
						<text>更多咨询师</text>
						<u-icon name="arrow-right" size="24" color="#6c8eef"></u-icon>
					</view>
				</view>
				
				<view class="consultant-list">
					<view v-for="(item, index) in consultants" :key="index" class="consultant-card">
						<view class="card-header">
							<view class="avatar-container">
								<u-image :src="item.avatar" width="120rpx" height="120rpx" shape="circle"></u-image>
								<view class="rating-badge" v-if="item.rating">
									<u-icon name="star-fill" color="#FFD700" size="24"></u-icon>
									<text>{{item.rating}}</text>
								</view>
							</view>
							<view class="info-container">
								<view class="name-row">
									<text class="name">{{ item.name }}</text>
									<view class="tags">
										<text class="tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{tag}}</text>
									</view>
								</view>
								<view class="expertise">
									<text class="label">擅长：</text>
									<text class="value">{{ item.expertise }}</text>
								</view>
								<view class="experience">
									<text class="label">从业经验：</text>
									<text class="value">{{ item.experience || 0 }}年</text>
								</view>
							</view>
							<button class="appointment-btn" @click="handleAppointment(item)">
								<u-icon name="calendar" size="24" color="#ffffff"></u-icon>
								<text>立即预约</text>
							</button>
						</view>
					</view>
				</view>
			</view>

			<!-- 我的问卷 -->
			<view class="module-card" @click="navigateTo('/testPages/questionnaire/questionnaire')">
				<view class="module-icon">
					<u-icon name="file-text-fill" color="#6c8eef" size="40"></u-icon>
				</view>
				<view class="module-content">
					<text class="module-title">我的问卷</text>
					<text class="module-desc">专业的心理测评问卷</text>
				</view>
				<u-icon name="arrow-right" color="#999" size="32"></u-icon>
			</view>

			<!-- 心理小游戏 -->
			<view class="module-card" @click="navigateTo('/gamePages/games/games')">
				<view class="module-icon">
					<u-icon name="play-circle-fill" color="#6c8eef" size="40"></u-icon>
				</view>
				<view class="module-content">
					<text class="module-title">心理小游戏</text>
					<text class="module-desc">轻松有趣的心理游戏</text>
				</view>
				<u-icon name="arrow-right" color="#999" size="32"></u-icon>
			</view>

			<!-- 留言平台 -->
			<view class="module-card" @click="navigateTo('/gamePages/message/message')">
				<view class="module-icon">
					<u-icon name="chat-fill" color="#6c8eef" size="40"></u-icon>
				</view>
				<view class="module-content">
					<text class="module-title">留言平台</text>
					<text class="module-desc">分享你的心情故事</text>
				</view>
				<u-icon name="arrow-right" color="#999" size="32"></u-icon>
			</view>

			<!-- AI聊天 -->
			<!-- <view class="module-card" @click="navigateTo('/pages/chat/chat')">
				<view class="module-icon">
					<u-icon name="server-fill" color="#6c8eef" size="40"></u-icon>
				</view>
				<view class="module-content">
					<text class="module-title">AI聊天</text>
					<text class="module-desc">智能心理助手</text>
				</view>
				<u-icon name="arrow-right" color="#999" size="32"></u-icon>
			</view> -->
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isChecking: true,
				userInfo: {
					name: '',
					avatar: ''
				},
				consultants: [],
			}
		},
		async onLoad(options) {
			const token = uni.getStorageSync('uni_id_token');
		
			// 如果本地没有 token，跳转登录
			if (!token) {
				uni.redirectTo({
					url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
				});
				return;
			}
		
			// 云函数调用 checkToken，并自动续签（根据配置）
			const res = await uniCloud.callFunction({
				name: 'checkToken', // 你需确保这个云函数已创建，代码见下方
				data: {
					uniIdToken: token
				}
			});
		
			// token 无效，跳转登录
			if (res.result.code !== 0) {
				uni.removeStorageSync('uni_id_token');
				uni.removeStorageSync('uni_id_token_expired');
				uni.redirectTo({
					url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
				});
				return;
			}
		
			// 如果返回了新 token，更新本地存储
			if (res.result.token) {
				uni.setStorageSync('uni_id_token', res.result.token);
				uni.setStorageSync('uni_id_token_expired', Date.now() + res.result.tokenExpired * 1000);
			}
		
			// token 有效，加载数据
			await Promise.all([
				this.checkUserStatus(),
				this.getUserInfo(),
				this.loadConsultants()
			]);
		
			this.isChecking = false;
		},

		methods: {
			async checkUserStatus() {
			  try {
				const token = uni.getStorageSync('uni_id_token');
				if (!token) {
				  uni.redirectTo({
					url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
				  });
				  return false;
				}

				// 检查hasSkippedTest的值
				const hasSkippedTest = uni.getStorageSync('hasSkippedTest');
				if (hasSkippedTest === true) {
				  // 如果hasSkippedTest为true，则不跳转到index界面
				  return false;
				}

				// 调用两个云函数检查状态
				const [testRes, cancelRes] = await Promise.all([
				  uniCloud.callFunction({
					name: 'checkTestFrequency',
					data: { uniIdToken: token }
				  }),
				  uniCloud.callFunction({
					name: 'checkUserRemainCancelCount',
					data: { uniIdToken: token }
				  })
				]);

				if ((testRes.result.code === 0 && testRes.result.needTest) ||
					(cancelRes.result.code === 0 && cancelRes.result.needTest)) {
				  uni.redirectTo({
					url: '/testPages/mindTest/mindTest'
				  });
				  return false;
				}

				if (testRes.result.code === -4 || cancelRes.result.code === -4) {
				  uni.showToast({
					title: '获取测试状态失败',
					icon: 'none'
				  });
				  console.warn('测试状态失败:', testRes.result.message || cancelRes.result.message);
				}

				return true;
			  } catch (error) {
				console.error('用户状态检查失败:', error);
				uni.showToast({
				  title: '状态检查异常',
				  icon: 'none'
				});
				return false;
			  }
			},

			async loadConsultants() {
				try {
					const res = await uniCloud.callFunction({
						name: 'getConsultants'
					});
					let allConsultants = res.result.data.consultants || [];
					allConsultants.sort((a, b) => (b.rating || 0) - (a.rating || 0));		
					this.consultants = allConsultants.slice(0, 2);
					

				} catch (error) {
					console.error('获取咨询师数据失败:', error);
				}
			},
			navigateToList() {
				uni.navigateTo({
					url: '/pages/consultants/full-list'
				});
			},
			handleAppointment(consultant) {
				uni.navigateTo({
					url: `/pages/appointment/appoint?uniIdToken=${consultant.uniIdToken}`
				});
			},
			async getUserInfo() {
				try {
					const token = uni.getStorageSync('uni_id_token');
					if (!token) {
						uni.navigateTo({
							url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
						});
						return;
					}

					const res = await uniCloud.callFunction({
						name: 'getUserInfo',
						data: {
							uniIdToken: token
						}
					});

					if (res.result && res.result.code === 0) {
						this.userInfo.name = res.result.data.nickname;
						this.userInfo.avatar = res.result.data.avatar_file.url;
					}
				} catch (error) {
					console.error('获取用户信息失败:', error);
				}
			},
			navigateTo(url) {
				uni.navigateTo({
					url: url
				});
			}
		}
	}
</script>

<style lang="scss">
	/* 启动加载样式 */
	.loading {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		width: 100%;
	}

	/* 主内容区样式 */
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.welcome-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 30rpx;
		background: linear-gradient(135deg, rgba(108, 142, 239, 0.8) 0%, rgba(74, 111, 227, 0.8) 100%);
		border-radius: 0 0 30rpx 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.1);
		margin-bottom: 30rpx;

		.welcome-text {
			.greeting {
				font-size: 32rpx;
				color: rgba(255, 255, 255, 0.9);
			}
			.username {
				font-size: 36rpx;
				font-weight: bold;
				color: #ffffff;
				margin-left: 10rpx;
			}
		}

		.user-avatar {
			.avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				border: 4rpx solid rgba(255, 255, 255, 0.3);
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			}
		}
	}

	.modules-section {
		padding: 0 30rpx;
	}

	.consultant-section {
		margin-bottom: 30rpx;
		background: #ffffff;
		border-radius: var(--radius-md);
		padding: 30rpx;
		box-shadow: var(--shadow-md);
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		
		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: var(--text-color);
			position: relative;
			padding-left: 20rpx;

			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				width: 8rpx;
				height: 32rpx;
				background: #6c8eef;
				border-radius: 4rpx;
			}
		}
		
		.more-btn {
			display: flex;
			align-items: center;
			color: var(--primary-color);
			font-size: 28rpx;
			
			text {
				margin-right: 8rpx;
			}
		}
	}

	.consultant-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.consultant-card {
		background: #ffffff;
		border-radius: var(--radius-sm);
		overflow: hidden;
		transition: all 0.3s ease;
		margin-bottom: 20rpx;
		
		&:active {
			transform: translateY(2rpx);
			box-shadow: var(--shadow-sm);
		}
	}

	.card-header {
		padding: 20rpx;
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.avatar-container {
		position: relative;
		flex-shrink: 0;
		
		.rating-badge {
			position: absolute;
			right: -10rpx;
			bottom: -10rpx;
			background: #ffffff;
			border-radius: 20rpx;
			padding: 4rpx 12rpx;
			display: flex;
			align-items: center;
			box-shadow: var(--shadow-sm);
			
			text {
				color: #FFD700;
				font-size: 24rpx;
				margin-left: 4rpx;
			}
		}
	}

	.info-container {
		flex: 1;
		min-width: 0;
		
		.name-row {
			display: flex;
			align-items: center;
			margin-bottom: 12rpx;
			flex-wrap: wrap;
			
			.name {
				font-size: 30rpx;
				font-weight: 600;
				color: var(--text-color);
				margin-right: 16rpx;
			}
			
			.tags {
				display: flex;
				gap: 8rpx;
				flex-wrap: wrap;
				
				.tag {
					font-size: 22rpx;
					color: var(--primary-color);
					background: rgba(108, 142, 239, 0.1);
					padding: 4rpx 12rpx;
					border-radius: 12rpx;
				}
			}
		}
		
		.expertise, .experience {
			font-size: 26rpx;
			color: #666;
			margin-top: 8rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			
			.label {
				color: #999;
				margin-right: 8rpx;
			}
			
			.value {
				color: #666;
			}
		}
	}

	.appointment-btn {
		display: flex;
		align-items: center;
		background: #6c8eef;
		border: none;
		padding: 8rpx 20rpx;
		border-radius: 30rpx;
		transition: all 0.3s ease;
		flex-shrink: 0;
		height: fit-content;
		
		&:active {
			transform: translateY(2rpx);
			background: #5a7de0;
			box-shadow: 0 4rpx 8rpx rgba(108, 142, 239, 0.3);
		}
		
		.u-icon {
			margin-right: 6rpx;
		}
		
		text {
			color: #ffffff;
			font-size: 24rpx;
		}
	}

	.module-card {
		display: flex;
		align-items: center;
		background: white;
		padding: 30rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.1);
		transition: all 0.3s ease;

		&:active {
			transform: translateY(-2rpx);
			box-shadow: 0 8rpx 16rpx rgba(108, 142, 239, 0.2);
		}

		.module-icon {
			width: 80rpx;
			height: 80rpx;
			background: rgba(108, 142, 239, 0.1);
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx;
		}

		.module-content {
			flex: 1;

			.module-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
				margin-bottom: 16rpx;
				display: block;
			}

			.module-desc {
				font-size: 24rpx;
				color: #666;
				display: block;
				line-height: 1.4;
			}
		}
	}

	.user-info {
		background: linear-gradient(135deg, #6c8eef 0%, #4a6fe3 100%);
		padding: 40rpx 30rpx;
		border-radius: 0 0 40rpx 40rpx;
		box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.2);
		
		.greeting {
			color: #ffffff;
			font-size: 36rpx;
			font-weight: 500;
			margin-bottom: 20rpx;
		}
		
		.user-avatar {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			border: 4rpx solid rgba(255, 255, 255, 0.3);
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		}
	}
</style>
